import React, { useState, useRef } from 'react';
import { EditableProTable } from '@ant-design/pro-table';
import { Button, message, Upload } from 'antd';
import { UploadOutlined, DownloadOutlined } from '@ant-design/icons';
import { queryRule, updateRule, addRule, removeRule } from './service';

const EditTable = (props) => {
  const [editableKeys, setEditableRowKeys] = useState([]);
  const [dataSource, setDataSource] = useState([]);
  const [position, setPosition] = useState('top');
  const [count, setCount] = useState({});
  const actionRef = useRef();

  const columns = [
    {
      title: '名称',
      dataIndex: 'name',
      editable: (text, record, index) => {
        return index !== 1;
      },
      width: '25%',
    },
    {
      title: 'key',
      dataIndex: 'configKey',
      width: '20%',
    },
    {
      title: 'value',
      dataIndex: 'configValue',
      width: '20%',
    },
    {
      title: '状态',
      dataIndex: 'dataType',
      valueType: 'select',
      width: '15%',
      valueEnum: {
        string: { text: '字符串', status: 'Default' },
        int: {
          text: '数字',
          status: 'Processing',
        },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="editable"
          onClick={() => {
            var _a;
            (_a = action.startEditable) === null || _a === void 0
              ? void 0
              : _a.call(action, record.id);
          }}
        >
          编辑
        </a>,
      ],
    },
  ];
  const uploadOnChange = (info) => {
    if (info.file.status === 'done') {
      actionRef.current.reload();
      message.success('导入成功');
    } else {
      message.error('导入失败请重试！');
    }
  };
  const add = () => {
    return {
      id: (Math.random() * 1000000).toFixed(0),
      dataType: 'string',
      isAdd: true,
    };
  };

  const addArr = async (record) => {
    if (record.isAdd === true) {
      const hide = message.loading('正在添加');

      try {
        await addRule({ ...record });
        hide();
        message.success('添加成功');
        actionRef.current.reload();
        return true;
      } catch (error) {
        hide();
        message.error('添加失败请重试！');
        return false;
      }
    } else {
      const newData = [...dataSource];
      const index = newData.findIndex((item) => record.id === item.id);

      const hide = message.loading('正在修改');

      try {
        const response = await updateRule({
          configKey: record.configKey,
          configValue: record.configValue,
          id: record.id,
          dataType: record.dataType,
          version: record.version + 1,
        });
        if (response.code === 999) {
          throw new Error();
        }
        hide();
        message.success('修改成功');
        actionRef.current.reload();
        // if (index > -1) {
        //   //编辑时候
        //   const item = newData[index];
        //   newData.splice(index, 1, { ...item, ...record });
        //   setDataSource(newData);
        // } else {
        //   newData.push(record);
        //   setDataSource(newData);
        // }
        return true;
      } catch (error) {
        hide();
        message.error('修改失败请重试！');
        return false;
      }
    }
  };
  const deleteArr = async (record) => {
    const hide = message.loading('正在删除');
    const newData = [...dataSource];
    const index = newData.findIndex((item) => record.id === item.id);
    try {
      await removeRule(record.id);
      hide();
      // message.success('删除成功，即将刷新');
      newData.splice(index, 1);
      setDataSource(newData);
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };
  return (
    <div>
      <EditableProTable
        rowKey="id"
        headerTitle="配置列表"
        recordCreatorProps={{
          position,
          record: add(),
        }}
        bordered
        actionRef={actionRef}
        columns={columns}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        postData={(payload) => {
          const { list, total } = payload;
          setCount(total);
          setDataSource(list);
          return list || [];
        }}
        toolBarRender={() => {
          return [
            <Upload
              name="multipartFile"
              action={() => {
                return `/factory/terminal/config/template/importFile`;
              }}
              listType="picture"
              showUploadList={false}
              maxCount={1}
              onChange={uploadOnChange}
              headers={{ token: sessionStorage.getItem('token'), type: 'ADMIN' }}
            >
              <Button type="primary" icon={<DownloadOutlined />}>
                导入
              </Button>
            </Upload>,
          ];
        }}
        pagination={{
          showSizeChanger: false,
          showQuickJumper: true,
          position: ['bottomCenter'],
          size: 'small',
          defaultPageSize: 30,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        value={dataSource}
        editable={{
          editableKeys,
          onSave: (k, r) => {
            addArr(r);
          },
          onDelete: (k, r) => {
            deleteArr(r);
          },
          onChange: setEditableRowKeys,
        }}
      />
    </div>
  );
};

export default EditTable;
